package com.witframework.remote;

import org.apache.commons.beanutils.MethodUtils;

import com.thoughtworks.xstream.XStream;

/**
 * 简单远程调用请求解析执行类
 * @author wuxinyang
 *
 */
class LocalRequestProcessor {
	public static Object processorLocalhost(RemoteRequest request){
		String serviceName = request.getServiceName();
		try {
			Object service;
			if(request.getServiceType().equalsIgnoreCase("spring")){
				service=com.witframework.core.BeanFactory.getBean(serviceName);
			}
			else{
				service = Class.forName(serviceName).newInstance();
			}
			Object[] args=request.getArguments();
			if(request.isArgumentFromXml()&&args!=null){		
				Object[] objArgs=new Object[args.length];
				for(int i=0;i<args.length;i++){						
					objArgs[i]=new XStream().fromXML((String)args[i]);
				}				
				args=objArgs;
			}
			Object object= MethodUtils.invokeMethod(service, request.getMethodName(),args);
			if(request.isResultAsXml()){
				//object=Java2Xml.toXml(object);
				object=new XStream().toXML(object);
			}
			return object;
		} catch (Exception e) {
			return new RemoteException("处理远程调用时发生错误.",e);
		}
	}
}
